package com.qbccn.onlinetest.config.custom;

import com.alibaba.fastjson.JSONObject;
import com.qbccn.onlinetest.domain.OtUser;
import com.qbccn.onlinetest.service.UserService;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

/**
 * @author linke
 * @date 2020/5/23 18:24
 * @description 用户登录成功时返回给前端的数据
 */
@Component
public class AjaxAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

  @Autowired
  private UserService userService;

  @Override
  public void onAuthenticationSuccess(HttpServletRequest httpServletRequest,
      HttpServletResponse httpServletResponse, Authentication authentication)
      throws IOException, ServletException {
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("code", 0);
    jsonObject.put("message", "登录成功！");
    //让浏览器用utf8来解析返回的数据
    httpServletResponse.setHeader("Content-type", "application/json; charset=utf-8");
    httpServletResponse.setCharacterEncoding("UTF-8");//防止中文乱码
    httpServletResponse.getWriter().write(jsonObject.toJSONString());

    Authentication authenticationToken = SecurityContextHolder.getContext().getAuthentication();
    User userDetails = (User) authenticationToken.getPrincipal();
    OtUser user = userService.getUserInfo(userDetails.getUsername());
    httpServletRequest.getSession().setAttribute("username", user.getUsername());
    httpServletRequest.getSession().setAttribute("name", user.getName());
    httpServletRequest.getSession().setAttribute("imgUrl", user.getImgUrl());
  }
}
